package tools.twitter;

import java.util.regex.Pattern;

public class TweetTidy {
	private static Pattern urlPattern = Pattern.compile("(https?)://[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]", Pattern.CASE_INSENSITIVE);
	private static Pattern atPattern = Pattern.compile("@[^ ]+");
	private static Pattern hashPattern = Pattern.compile(" #[^ ]+");
	private static Pattern emitSpaces = Pattern.compile("\\s+");
	private static String [] HTMLSpecial = {"&#39;","&quot;","&amp;","&lt;","&gt;", "&#8230;", "…"};
	private static String [] HTMLSpecialReplacement = {"'","\"","&","<",">", "...", "..."};
	private static Pattern [] HTMLSpecialPattern;
	
	static {
		HTMLSpecialPattern = new Pattern[HTMLSpecial.length];
		for (int i = 0; i < HTMLSpecial.length; i++) {
			String special = HTMLSpecial[i];
			HTMLSpecialPattern[i] = Pattern.compile(special);
		}
	}
	
	/**
	 * Tidy the html content to replace all the HTML special characters such as &quot;(")
	 * @param original
	 * @return tidy content
	 */
	public static String doTidyHTML(String original) {
		String tidy = original.trim();
		
		// special HTML characters
		for (int i = 0; i < HTMLSpecialPattern.length; i++) {
			tidy = HTMLSpecialPattern[i].matcher(tidy).replaceAll(HTMLSpecialReplacement[i]);
		}
		tidy = emitSpaces.matcher(tidy).replaceAll(" ");
		
		return tidy.trim();
	}
	
	/**
	 * Tidy the html content to replace all the HashTags
	 * @param original
	 * @return tidy content
	 */
	public static String doTidyHashTag(String original) {
		// #tags
		String tidy = hashPattern.matcher(original).replaceAll(" ");
		tidy = emitSpaces.matcher(tidy).replaceAll(" ");
		return tidy.trim();
	}
	
	/**
	 * Tidy the html content to replace all the AT tags
	 * @param original
	 * @return tidy content
	 */
	public static String doTidyATTag(String original) {
		// #tags
		String tidy = atPattern.matcher(original).replaceAll(" ");
		tidy = emitSpaces.matcher(tidy).replaceAll(" ");
		return tidy.trim();
	}
	
	/**
	 * Tidy special characters, At tags, Hash tags, urls
	 * @param original
	 * @return tidy content
	 */
	public static String doTidyAll(String original) {
		String tidy = doTidyHTML(original);
		// URLs
		tidy = urlPattern.matcher(tidy).replaceAll("");
		// @tags
		tidy = atPattern.matcher(tidy).replaceAll("");
		// #tags
		tidy = hashPattern.matcher(tidy).replaceAll(" ");
		
		tidy = emitSpaces.matcher(tidy).replaceAll(" ");
		
		return tidy.trim();
	}
}
